package com.admin.controller.admin;


import com.github.pagehelper.PageInfo;
import com.system.annotation.Log;
import com.system.constant.HTTPStatus;
import com.system.emus.BusinessType;
import com.system.entity.Permission;
import com.system.entity.RolePermission;
import com.system.response.Result;
import com.system.response.permission.PermissionDtoResponse;
import com.system.service.PermissionService;
import com.system.util.FileUtil;
import com.system.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 权限表 前端控制器
 * </p>
 *
 * @author zfc
 * @since 2023-04-20
 */
@RequiresAuthentication
@Validated
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @Cacheable(value = "permission",key = "#root.methodName")
    @GetMapping("/all")
    @ApiOperation("查询所有权限(绑定角色)")
    public Result all(){
        return permissionService.all();
    }

    @Cacheable(
            value = "permission",
            key = "#permissionDto.pageSize +'::'+ #permissionDto.pageNum +'::'+ #permissionDto.key +'::'+ #permissionDto.delete")
    @PostMapping("/limit")
    @ApiOperation("分页查询权限，根据条件")
    public Result limit(@RequestBody PermissionDtoResponse permissionDto){
        return permissionService.limitPermission(permissionDto);
    }

    @Log(title = "权限管理",businessType = BusinessType.INSERT)
    @CacheEvict(value = "permission",allEntries = true)
    @RequiresPermissions("admin:permission:add")
    @PostMapping("/addPermission")
    @ApiOperation("新增权限")
    public Result addPermission(@Validated @RequestBody Permission permission){
        boolean unique = permissionService.checkPermissionUnique(permission);
        if (unique){
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("权限【"+permission.getPermissionKey()+"】已存在。");
        }else {
            boolean addPerssion = permissionService.addPerssion(permission);
            if (addPerssion){
                return new Result().setCode(HTTPStatus.SUCCESS).setMessage("权限【"+permission.getPermissionKey()+"】新增成功。");
            }else {
                return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("权限【"+permission.getPermissionKey()+"】新增失败，请联系管理员！");
            }
        }
    }
    
    @Log(title = "权限管理",businessType = BusinessType.UPDATE)
    @CacheEvict(value = "permission",allEntries = true)
    @RequiresPermissions("admin:permission:update")
    @PutMapping("/updatePermission")
    @ApiOperation("修改权限")
    public Result updatePermission(@Validated @RequestBody Permission permission){

        //检查修改的名称是否存在，如果修改名称还是原名称则可以修改
        boolean isOneself = permissionService.checkPermissionKeyIsOneself(permission);


        boolean unique = permissionService.checkPermissionUnique(permission);

        if (unique && isOneself) {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("权限【" + permission.getPermissionKey() + "】已存在。");
        }
        boolean updateRole = permissionService.updatePerssion(permission);

        if (updateRole) {
            return new Result().setCode(HTTPStatus.SUCCESS).setMessage("权限【"+permission.getPermissionKey()+"】修改成功。");
        } else {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("权限【"+permission.getPermissionKey()+"】修改失败，请联系管理员！");
        }
    }

    @Cacheable(
            value = "permission",
            key = "#root.methodName +'::'+ #id"
    )
    @GetMapping("/selectPermissionById")
    @ApiOperation("查询权限通过权限编号")
    public Result selectPermissionById(@NotNull(message = "编号不能为空") Integer id){
        Permission permission = permissionService.selectPermission(id);
        return new Result<>().setCode(HTTPStatus.SUCCESS).setData(permission);
    }

    @Log(title = "权限管理",businessType = BusinessType.FREEZE)
    @CacheEvict(value = "permission",allEntries = true)
    @RequiresPermissions("admin:permission:delete")
    @DeleteMapping("/batchDeletePermission")
    @ApiOperation("批量删除权限（修改权限状态）")
    public Result batchUpdatePermission(@NotNull(message = "权限编号不能为空") Integer[]ids,
                                        @NotNull(message = "状态不存在") Integer isDelete){
        return  permissionService.batchUpdatePermissionStatus(ids, isDelete);
    }
    @Log(title = "权限管理",businessType = BusinessType.DELETE)
    @CacheEvict(value = "permission",allEntries = true)
    @RequiresPermissions("admin:permission:completelyDelete")
    @DeleteMapping("/batchCompletelyDeletePermission")
    @ApiOperation("批量彻底删除权限")
    public Result batchDeletePermission(@NotNull(message = "编号不能为空") Integer[]ids) {
        boolean completelyDeleteById = permissionService.batchDeletePermission(ids);
        if (completelyDeleteById) {
            return new Result().setCode(HTTPStatus.SUCCESS).setMessage("批量删除成功。");
        } else {
            return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("批量删除失败，请联系管理员！");
        }
    }

    @Log(title = "权限管理",businessType = BusinessType.EXPORT)
    @GetMapping("/downloadPermissionTemplates")
    @ApiOperation("下载批量新增权限模板")
    public void downloadPermissionTemplates(HttpServletRequest request, HttpServletResponse response){
        try {
            FileUtil.downLoadBatchAddTemplate("批量添加权限模板.xlsx",request,response);
        } catch (IOException e) {
            throw new RuntimeException("模板下载失败，请联系管理员！");
        }
    }

    @Log(title = "权限管理",businessType = BusinessType.IMPORT)
    @CacheEvict(value = "permission",allEntries = true)
    @RequiresPermissions("admin:permission:add")
    @PostMapping("/uploadPermissionTemplates")
    @ApiOperation("上传权限模板")
    public Result uploadPermissionTemplates(@RequestPart("permissionFile")MultipartFile file) throws IOException{
        //调用解析工作簿的工具类
        Sheet sheet = FileUtil.parseFileGetSheetData(file);
        //通过工作簿的内容，遍历出权限数据
        List<Permission> permissions = FileUtil.parseUploadSheetPermissionTemplate(sheet);

        if (permissions.size() <= 0){
            return  new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("解析导入权限数据为空！");
        }

        for (int i = 0; i < permissions.size(); i++) {
            if (StringUtils.isNull(permissions.get(i).getPermissionKey().trim())){
                return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("权限名不能为空");
            }
            for (int i1 = 0; i1 < permissions.size(); i1++) {
                //检查导入的权限是否存在重复
                if (i!=i1 && permissions.get(i).getPermissionKey().equals(permissions.get(i1).getPermissionKey())){
                    return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("权限"+permissions.get(i).getPermissionKey()+"不能重复导入！");
                }
            }
        }
        boolean b = permissionService.batchAdditionPermission(permissions);

        if (b) {
            return new Result().setCode(HTTPStatus.SUCCESS).setMessage("权限导入成功。");
        }
        return new Result().setCode(HTTPStatus.BAD_REQUEST).setMessage("权限导入失败，请联系管理员！");
    }



}
